package com.aliyun.oss.interceptor;

import com.aliyun.oss.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class TokenInterceptor implements HandlerInterceptor {
//    排除路径
    private static final String[] EXCLUDE_PATHS={
            "/login"
    };
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        检查是否在排除路径中
        String requestURI = request.getRequestURI();
//        StringBuffer requestURL = request.getRequestURL();
//        System.out.println("213"+requestURL);
//        System.out.println("！！！"+requestURI);
        for (String path : EXCLUDE_PATHS) {
            if (requestURI.startsWith(path)) {
//                System.out.println("!!!!--1");
                return true;
            }
        }
        // 放行OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
//            System.out.println("!!!!--0 OPTIONS请求放行");
            return true;
        }
        String token = request.getHeader("Authorization");
//        System.out.println("???"+token);
        if(token==null||token.isEmpty()){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            System.out.println("!!!!--2");
            return false;
        }
        if(!JwtUtils.validateToken(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            System.out.println("!!!!--3");
            return false;
        }
//        存储userId
        Claims claims = JwtUtils.analysisToken(token);
        Integer id = Integer.parseInt(String.valueOf(claims.get("id")));
        request.setAttribute("id",id);
//        System.out.println("!!!!--4");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
